import React from 'react';
import { Table, Button, Typography, Space, Tooltip, Tag, Card, Row, Col, Statistic, Empty, Modal, Drawer } from 'antd';
import { ShopOutlined, DollarOutlined, InboxOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { WarehouseState, InventoryItem } from '../types/game';
import { ItemManager } from '../utils/itemManager';

const { Title, Text } = Typography;

interface WarehouseDrawerProps {
  warehouse: WarehouseState;
  open: boolean;
  onClose: () => void;
  onSellItem?: (itemId: string, quantity: number) => number;
}

const WarehouseDrawer: React.FC<WarehouseDrawerProps> = ({
  warehouse,
  open,
  onClose,
  onSellItem
}) => {
  const handleSellItem = (item: InventoryItem) => {
    if (!item.sellable) {
      Modal.warning({
        title: '无法出售',
        content: '这个物品不能出售！',
      });
      return;
    }
    
    const sellValue = ItemManager.getItemValue(item);
    const displayName = ItemManager.getItemDisplayName(item);
    
    Modal.confirm({
      title: '确认出售',
      content: (
        <div>
          <p>确定要出售 <strong style={{ color: ItemManager.getRarityColor(item.rarity) }}>{displayName}</strong> 吗？</p>
          <p>出售价格：<Text type="warning">{sellValue} 搜币</Text></p>
        </div>
      ),
      okText: '确认出售',
      cancelText: '取消',
      onOk: () => {
        if (onSellItem) {
          const earnedCoins = onSellItem(item.id, 1);
          if (earnedCoins > 0) {
            Modal.success({
              title: '出售成功！',
              content: `获得 ${earnedCoins} 搜币`,
            });
          }
        }
      },
    });
  };



  const columns: ColumnsType<InventoryItem> = [
    {
      title: '物品名称',
      dataIndex: 'name',
      key: 'name',
      width: '40%',
      render: (_, item) => {
        const displayName = ItemManager.getItemDisplayName(item);
        const rarityColor = ItemManager.getRarityColor(item.rarity);
        const rarityName = ItemManager.getRarityName(item.rarity);
        const itemValue = ItemManager.getItemValue(item);
        
        return (
          <Tooltip
            title={
              <div>
                <div><strong>{displayName}</strong></div>
                <div style={{ margin: '8px 0' }}>{item.description}</div>
                <div>稀有度：<Tag color={rarityColor}>{rarityName}</Tag></div>
                <div>价值：{itemValue} 搜币</div>
                {!item.sellable && <div style={{ color: '#ff7875' }}>※ 此物品不可出售</div>}
              </div>
            }
            placement="topLeft"
          >
            <Space>
              <Text 
                strong 
                style={{ color: rarityColor, cursor: 'help' }}
              >
                {displayName}
              </Text>
              <Tag color={rarityColor}>
                {rarityName}
              </Tag>
            </Space>
          </Tooltip>
        );
      },
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: '20%',
      render: (type) => ItemManager.getTypeDisplayName(type),
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: '15%',
      align: 'center',
      render: (quantity) => <Text strong>{quantity}</Text>,
    },
    {
      title: '操作',
      key: 'action',
      width: '25%',
      align: 'center',
      render: (_, item) => (
        <Space>
          {item.sellable ? (
            <Button 
              type="primary"
              size="small"
              icon={<ShopOutlined />}
              onClick={() => handleSellItem(item)}
              disabled={item.quantity <= 0}
            >
              出售
            </Button>
          ) : (
            <Text type="secondary">不可出售</Text>
          )}
        </Space>
      ),
    },
  ];

  const sortedItems = [...warehouse.items].sort((a, b) => {
    // 按稀有度排序（稀有度高的在前），然后按类型和名称排序
    const rarityOrder = { legendary: 0, epic: 1, rare: 2, uncommon: 3, common: 4 };
    const rarityDiff = rarityOrder[a.rarity] - rarityOrder[b.rarity];
    if (rarityDiff !== 0) return rarityDiff;
    
    if (a.type !== b.type) {
      return a.type.localeCompare(b.type);
    }
    return a.name.localeCompare(b.name);
  });

  return (
    <Drawer
      title="仓库"
      placement="right"
      open={open}
      onClose={onClose}
      width={720}
      destroyOnClose
    >
      {/* 仓库统计信息 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={24}>
          <Card>
            <Row gutter={16}>
              <Col span={8}>
                <Statistic 
                  title="仓库" 
                  value={warehouse.items.length} 
                  suffix={`/ ${warehouse.capacity}`}
                  prefix={<InboxOutlined />}
                />
              </Col>
              <Col span={8}>
                <Statistic 
                  title="搜币" 
                  value={warehouse.coins} 
                  prefix={<DollarOutlined />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
              <Col span={8}>
                <Statistic 
                  title="物品种类" 
                  value={new Set(warehouse.items.map(item => item.id)).size}
                  prefix={<ShopOutlined />}
                />
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      {/* 仓库表格 */}
      <Card title={<Title level={4} style={{ margin: 0 }}>仓库物品</Title>}>
        {warehouse.items.length === 0 ? (
          <Empty
            image={<InboxOutlined style={{ fontSize: 64, color: '#d9d9d9' }} />}
            description={
              <div>
                <div>仓库空空如也...</div>
                <div style={{ color: '#8c8c8c', marginTop: 8 }}>
                  完成游戏后，你的物品会自动存放在这里
                </div>
              </div>
            }
          />
        ) : (
          <Table
            columns={columns}
            dataSource={sortedItems.map((item, index) => ({
              ...item,
              key: `${item.id}-${index}`,
            }))}
            pagination={{
              pageSize: 8,
              showSizeChanger: false,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `第 ${range[0]}-${range[1]} 项，共 ${total} 项`,
            }}
            size="small"
          />
        )}
      </Card>
    </Drawer>
  );
};

export default WarehouseDrawer;